package ddbs;

import java.util.Iterator;
import java.util.List;

public class Workload implements JobDoneCallback {
    String sql;
    List<LocalWork> wks = null;
    int donecnt;
    JobDoneCallback donecb = null;
    Data data = null;
    boolean is_done = false;
    PeerMgr pm = null;

    public Workload(PeerMgr pm, String sql) {
        this.donecnt = 0;
        this.pm = pm;
        this.sql = sql;
        this.wks = SQLParse.parse(pm, sql);
        if (this.wks != null) {
            Iterator<LocalWork> it = this.wks.iterator();
            while (it.hasNext()) {
                LocalWork w = it.next();
                w.donecb = this;
            }
        } else {
            System.out.println("SQLParse failed " + sql);
        }
    }

    private void done() {
        if (donecb != null)
            donecb.jobdonecb(this);
    }

    void dealWith() {
        System.out.println("Deal with workload");
        if (this.wks == null) {
            this.is_done = true;
            return;
        }
        Iterator<LocalWork> it = this.wks.iterator();
        while (it.hasNext()) {
            LocalWork w = it.next();
            System.out.println("DealWith Work #"+ w.getId()+" assiginTo peer="+w.assignto.getId());
            //w.show(this.pm);
            w.dealWith();
        }
    }

    /*
     * merge dataSet in wks and fill this.data
     */
    private void merge() {
        if (this.wks != null) {
            Iterator<LocalWork> it = this.wks.iterator();
            while (it.hasNext()) {
                LocalWork w = it.next();
                if (w.data != null)
                    this.data = w.data.merge(this.data);
            }
        }
    }

    @Override
    public void jobdonecb(Object obj) {
        ++donecnt;
        if (donecnt == wks.size()) {
            is_done = true;
            merge();
            done();
        }
    }

    public void show() {
        System.out.println("SQL=[" + sql + "] wklist length=" + wks.size());

        Iterator<LocalWork> it = wks.iterator();
        int cnt = 0;
        while (it.hasNext()) {
            LocalWork w = it.next();
            System.out.println("=========================== show workload work "+cnt);
            System.out.println("#"+w.getId()+" "+w.getStatus() + " " + w.imsql);
            w.getDataSet().show();
            MSG msg = w.toMSG();
            msg.show();
            if (w.getStatus() == Work.STATUS) {
                Work sw = new SimpleWorkCreater(pm).fromMSG(msg);
                System.out.println(sw.formalSQL());
            } else {
                BinWork bw = new BinWorkCreater(pm).fromMSG(msg);
                System.out.println("w1: "+ bw.getW1().toString());
                System.out.println("w2: "+ bw.getW2().toString());
            }
            ++cnt;
        }
        System.out.println("=========================== show workload work end");
    }
}
